package cn.zhoutao.basic.controller;

import cn.zhoutao.basic.exception.BusinessException;
import cn.zhoutao.basic.util.AjaxResult;
import cn.zhoutao.basic.util.FastdfsUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @Author:MrZhou
 * @Date:2022/6/12 22:37
 * @RequestPart用来接收文件上传参数
 */
@RestController
@RequestMapping("/fastDfs")
public class FastDfsController {
    //文件上传接口
    @PostMapping("/upload")
    public AjaxResult upload(@RequestPart (value= "file",required = true)MultipartFile file){
        try {
            String filename = file.getOriginalFilename();
            String extName = filename.substring(filename.lastIndexOf(".") + 1);
            String path = FastdfsUtil.upload(file.getBytes(), extName);
            return AjaxResult.me().setResultObj(path);
        } catch (BusinessException e) {//自己的业务异常需要用自定义的异常处理
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage(e.getMessage());
        }catch (Exception e){
            e.printStackTrace();
            return  AjaxResult.me().setSuccess(false).setMessage("保存对象失败！"+e.getMessage());
        }
    }

    //文件删除接口
    @DeleteMapping
    public AjaxResult delete(@RequestParam String path){
        try {
            String pathTmp = path.substring(1);//group1/M00/00/05/CgAIC2Kl9liAI634AALPThcGgPw48.jpeg

            String group = pathTmp.substring(0, pathTmp.indexOf("/"));//group1
            String fileName = pathTmp.substring(pathTmp.indexOf("/") + 1);//M00/00/05/CgAIC2Kl9liAI634AALPThcGgPw48.jpeg
            FastdfsUtil.delete(group,fileName);
            return AjaxResult.me();
        }catch (BusinessException e){
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage(e.getMessage());
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("保存对象失败！"+e.getMessage());
        }
    }
}
